package com.cyj.mongodbcomment.cyj.service.impl;

import com.cyj.mongodbcomment.cyj.mapper.CommentMapper;
import com.cyj.mongodbcomment.cyj.pojo.Comment;
import com.cyj.mongodbcomment.cyj.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<Comment> findAll() {
        return commentMapper.findAll();
    }

    @Override
    public List<Map<String, Object>> findByArticleId(String articleid) {
        List<Map<String, Object>> result = new ArrayList<>();
        List<Comment> comments = commentMapper.findByArticleid(articleid);
        comments.forEach(comment -> {
            Map<String, Object> map = new HashMap<>();
            map.put("content",comment.getContent());
            map.put("nickname",comment.getNickname());
            map.put("time",comment.getCreatedatetime());
            result.add(map);
        });
        return result;
    }

    @Override
    public Comment findCommentById(String id) {
        return commentMapper.findById(id).get();
    }

    @Override
    public Page<Comment> findCommentListPageByParentid(String parentid, int page, int size) {
        return null;
    }

    @Override
    public Comment save(Comment comment, String articleid) {
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        comment.setCreatedatetime(bartDateFormat.format(date));
//      comment.set_id(id);
        comment.setLikenum(0);
        System.out.println(articleid);
        comment.setArticleid(articleid);
        return commentMapper.save(comment);
    }

    @Override
    public Comment update(Comment comment) {
        Comment comment1 =commentMapper.save(comment);
        return  comment1;
    }

    @Override
    public void deleteById(String id) {
        commentMapper.deleteById(id);
    }

    @Override
    public void updateCommentLikenumThumbup(String id) {
        //查询对象
        Query query=Query.query(Criteria.where("_id").is(id));
        //更新条件
        Update update = new Update();
        update.inc("likenum");

        //执行更新
        mongoTemplate.updateFirst(query,update,"comment");
    }
}
